package com.glowdayz.glowmee;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

	@SuppressWarnings("deprecation")
	private static void generateNotification(Context context, String message, String linkType, String linkCode) {
		
		int icon = R.drawable.appicon;
		long when = System.currentTimeMillis();

		NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

		Notification notification = new Notification(icon, message, when);

		String title = context.getString(R.string.app_name);

		Intent notificationIntent = null;
		
		if (linkType != null && linkType.equals("viewPouch")) {
			notificationIntent = new Intent(context, ViewPouch.class);
			notificationIntent.putExtra("PARAM_paramId", Integer.parseInt(linkCode));
		} else {
			notificationIntent = new Intent(context, MainActivity.class);
		}

		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		PendingIntent intent = PendingIntent.getActivity(context, 0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

		notification.setLatestEventInfo(context, title, message, intent);

		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		
		notification.defaults |= Notification.DEFAULT_SOUND;

		notificationManager.notify(0, notification);

	}

	@Override
	protected void onError(Context arg0, String arg1) {

	}

	@Override
	protected void onMessage(Context context, Intent intent) {

		String msg = intent.getStringExtra("msg");
		String linkType = intent.getStringExtra("linkType");
		String linkCode = intent.getStringExtra("linkCode");
		
		SharedPreferences prefs = getSharedPreferences("Save", MODE_PRIVATE);          
		if (prefs.getBoolean("push", true)) {
			generateNotification(context, msg, linkType, linkCode);
		}
	}

	@Override
	protected void onRegistered(Context context, String reg_id) {
		Log.e("키를 등록합니다.(GCM INTENTSERVICE)", reg_id);
	}

	@Override
	protected void onUnregistered(Context arg0, String arg1) {
		Log.e("키를 제거합니다.(GCM INTENTSERVICE)", "제거되었습니다.");
	}

}